<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <div class="body">
      <div class="project">
        <el-form
          :model="basicForm"
          label-position="top"
          :rules="basicRules"
          ref="basicFormRef"
        >
          <!-- 产出数据信息 -->
          <div class="project-part">
            <div class="project-part-title">
              产出数据信息
            </div>

            <el-row>
              <el-col :span="6">
                <el-form-item label="园区名称" prop="name">
                  <el-input
                    v-model="basicForm.name"
                    placeholder="请输入"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="责任单位">
                  <el-input
                    v-model="basicForm.unit"
                    placeholder="请输入"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="资产类型">
                  <el-select
                    placeholder="资产类型"
                    v-model="basicForm.type"
                    :disabled="isDetail"
                    @change="changeType"
                  >
                    <el-option
                      v-for="item in carrierTypeOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="园区建筑面积">
                  <el-input
                    v-model="basicForm.buildArea"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6">
                <el-form-item label="建筑密度(%)">
                  <el-input
                    v-model="basicForm.buildDensity"
                    type="number"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="停车位数量(个)">
                  <el-input
                    v-model="basicForm.parkCount"
                    type="number"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="绿地率(%)">
                  <el-input
                    v-model="basicForm.greenRate"
                    type="number"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="出租率">
                  <el-input
                    v-model="basicForm.rentRate"
                    type="number"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6">
                <el-form-item label="占地面积(亩)">
                  <el-input
                    v-model="basicForm.landArea"
                    type="number"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="住宅总货值(亿元)">
                  <el-input
                    v-model="basicForm.liveValue"
                    type="number"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item
                  label="地上建筑-住宅总面积(万平米)"
                >
                  <el-input
                    v-model="basicForm.landAreaTotal"
                    type="number"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="地上建筑-住宅总套数">
                  <el-input
                    v-model="basicForm.landLiveCount"
                    type="number"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6">
                <el-form-item
                  label="地上建筑-商业总面积(万平米)"
                >
                  <el-input
                    v-model="basicForm.landBusinessArea"
                    type="number"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="地上建筑-商业总套数">
                  <el-input
                    v-model="basicForm.landBusinessCount"
                    type="number"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="园区范围（shp格式）">
                  <el-upload
                    action="#"
                    class="shp-upload"
                    :show-file-list="false"
                    :drag="false"
                    :on-change="onFileSelect"
                    :auto-upload="false"
                    v-if="!isDetail"
                    accept=".zip"
                  >
                    <span>
                      <span class="shp-upload-icon"></span>
                      <span class="shp-upload-text"
                        >点击上传</span
                      >
                    </span>
                  </el-upload>
                  <el-input
                    v-model="fileName"
                    placeholder="暂无文件"
                    :disabled="isDetail"
                    clearable
                  ></el-input>
                  <el-progress
                    v-if="
                      progressNum !== 0 &&
                      progressNum !== 100
                    "
                    :percentage="progressNum"
                    color="#409eff"
                  ></el-progress>
                  <el-button
                    size="small"
                    class="preview-button"
                    @click="previewMap"
                    >地图预览</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6">
                <el-form-item label="园区简介">
                  <el-input
                    v-model="basicForm.introduce"
                    type="textarea"
                    placeholder="请输入"
                    :rows="6"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="园区图片">
                  <el-upload
                    ref="uploadRef"
                    class="hidden-upload"
                    action=""
                    :auto-upload="false"
                    :file-list="[]"
                    :show-file-list="false"
                    :on-change="handleChangeImage"
                    accept="image/*"
                  >
                  </el-upload>

                  <div class="upload-wrapper">
                    <img
                      v-if="previewUrl"
                      :src="previewUrl"
                      alt="点击替换图片"
                      class="upload-preview"
                      @click="triggerUpload"
                    />
                    <div
                      v-else
                      class="upload-placeholder"
                      @click="triggerUpload"
                    >
                      <i
                        class="el-icon-plus"
                        style="
                          font-size: 32px;
                          color: #909399;
                        "
                      ></i>
                    </div>
                  </div>
                  <!--
                  <el-dialog
                    :visible.sync="previewVisible"
                    width="50%"
                    v-if="!isDetail"
                  >
                    <img
                      :src="previewImage"
                      alt="预览"
                      style="width: 100%"
                    />
                  </el-dialog>
                  <el-image
                    v-for="item in fileList"
                    :preview-src-list="previewImageList"
                    :src="item.url"
                    class="image"
                  >
                  </el-image> -->
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 年度去化目标 -->
          <div class="project-part">
            <div class="project-part-title">
              年度去化目标
            </div>
            <el-button
              icon="el-icon-plus"
              @click="addPlan"
              class="add-btn"
              v-if="
                tableList.length <= yearList.length &&
                basicForm.type
              "
              >新增</el-button
            >

            <el-table
              :data="tableList"
              v-if="tableList.length"
              :header-cell-style="{
                background: '#F2F6FB',
                color: ' #6B767D'
              }"
              v-loading="loading"
              class="table"
            >
              <el-table-column label="年度">
                <template slot-scope="scope">
                  <el-select
                    placeholder="年度"
                    v-model="scope.row.year"
                    clearable
                  >
                    <el-option
                      v-for="item in yearList"
                      :key="item"
                      :label="item"
                      :value="item"
                      :disabled="
                        isOptionDisabled(item, scope.row)
                      "
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                v-if="basicForm.type !== '商品房'"
                label="本年度新增去化面积(平方米)"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.addYearArea"
                    type="number"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                v-if="basicForm.type !== '商品房'"
                label="本年度累计去化面积(平方米)"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.addYearTotalArea"
                    type="number"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                v-if="basicForm.type !== '商品房'"
                label="目标去化率"
              >
                <template slot-scope="scope">
                  <div
                    v-if="
                      scope.row.addYearTotalArea &&
                      basicForm.buildArea
                    "
                  >
                    {{
                      (
                        scope.row.addYearTotalArea /
                        basicForm.buildArea
                      ).toFixed(2)
                    }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                v-if="basicForm.type === '商品房'"
                label="本年度目标去化套数"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.addYearNumber"
                    type="number"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                v-if="basicForm.type === '商品房'"
                label="本年度目标去化产值(亿元)"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.addYearOutput"
                    type="number"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                width="180"
                v-if="basicForm.type === '商品房'"
                label="截止去年累计已去化套数"
              >
                <template slot-scope="scope">
                  <div>{{}}</div>
                </template>
              </el-table-column>
              <el-table-column
                width="250"
                v-if="basicForm.type === '商品房'"
                label="截止去年累计已去化产值(亿元)"
              >
                <template slot-scope="scope">
                  <div>{{}}</div>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                show-overflow-tooltip
                width="50"
              >
                <template slot-scope="scope">
                  <el-button
                    @click="deletePlan(scope.row.$index)"
                    type="text"
                    style="color: #ff5b5b; font-weight: 400"
                    v-has="'FixedInvestmentTarget:delete'"
                    >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </div>
    </div>
    <div class="line" v-show="!isDetail">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import { carrierTypeOptions } from '@/utils/project/data'
import {
  addParkInfo,
  uploadFileById,
  queryParkInfoById
} from '@/api/dataManagement'
import MapView from '@/components/mapView'
import Utool from '@/components/utool/index-land'
import customizeDialog from '@/components/checkHistory/customizeDialog.vue'
import { dwgFileById } from '@/api/projectMessage'
import * as turf from '@turf/turf'
import { STATIC_FILE_URL } from '@/api/config.js'
import request from '@/utils/request'

let _layerManager, _viewer

export default {
  props: {
    pkid: String,
    title: String,
    data: Object,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Breadcrumb,
    MapView,
    Utool,
    customizeDialog
  },
  data() {
    return {
      basicForm: {
        pkid: '',
        parkYearRelList: []
      },
      basicRules: {
        name: [
          {
            required: true,
            message: '请输入园区名称',
            trigger: 'blur'
          }
        ]
      },
      loading: false,
      props: { multiple: true },
      uploadLoading: false,
      progressNum: 0,
      dialogMapVisible: false,
      mapLoading: false,
      headerTitle: '',
      countMapLoad: 0,
      currentFeature: '',
      currentArea: 0,
      viewerId: 'dwgMap',
      fileName: '',
      shpFile: '',
      shpJson: '',
      parkRange: '',
      previewVisible: false,
      fileList: [],
      previewImageList: [],
      previewImage: '',
      uploadFile: '',
      yearList: [],
      tableList: [],
      previewUrl: ''
    }
  },
  computed: {
    titles() {
      return [this.title]
    },
    carrierTypeOptions() {
      return carrierTypeOptions
    }
  },
  watch: {
    fileName: function (val) {
      if (val === '') {
        this.basicForm.shpFile = ''
        this.basicForm.shpJson = ''
        this.basicForm.parkRange = ''
      }
    }
  },
  mounted() {
    if (this.pkid) {
      this.getParkInfo()
    }

    const year = new Date().getFullYear()
    this.yearList = [year, year - 1]
  },
  methods: {
    getParkInfo() {
      queryParkInfoById(this.pkid).then((res) => {
        if (res.success) {
          if (
            res.data.filePaths &&
            res.data.filePaths.length
          ) {
            const path = res.data.filePaths[0]
            const index = path.indexOf('upload')
            const img =
              index !== -1
                ? path.substring(
                    index + 'upload'.length + 1
                  )
                : ''
            this.previewUrl = `${STATIC_FILE_URL}${img}`
          }

          this.tableList = res.data.parkYearRelList
          this.basicForm = res.data
        }
      })
    },
    onFileSelect(file) {
      this.uploadLoading = true
      const data = new FormData()
      data.append('file', file.raw)
      request({
        method: 'post',
        url: '/pad/common/importData',
        data: data,
        onUploadProgress: (progressEvent) => {
          this.progressNum = parseInt(
            ((progressEvent.loaded / progressEvent.total) *
              100) |
              0,
            10
          )
        }
      })
        .then((res) => {
          if (res.success) {
            const id = res.data.fileId
            const geojson = res.data.geoJson
            this.$set(this.basicForm, 'fileName', file.name)
            this.$set(this.basicForm, 'shpFile', id)
            this.$set(this.basicForm, 'shpJson', geojson)
            this.$set(this.basicForm, 'parkRange', geojson)
            this.$message.success('上传成功')
          } else {
            this.$message.error(res.message)
          }

          this.uploadLoading = false
        })
        .catch(() => {
          this.uploadLoading = false
        })
    },

    previewMap() {
      if (this.basicForm.shpFile) {
        this.previewMapById(
          this.basicForm.shpFile,
          this.basicForm.shpJson
        )
        this.dialogMapVisible = true
      } else {
        this.$message.warning('请先上传文件再预览')
      }
    },

    previewMapById(id, geojsonStr) {
      this.headerTitle = '地图预览'
      this.mapLoading = true

      if (!geojsonStr) {
        dwgFileById(id)
          .then((res) => {
            if (res.success) {
              this.currentFeature = JSON.parse(res.data)
              const area = turf.area(this.currentFeature)
              this.currentArea = area ? area.toFixed(2) : 0
              // 更新地图预览
              this.countMapLoad++
            }
            this.mapLoading = false
          })
          .catch(() => {
            this.mapLoading = false
          })
      } else {
        this.currentFeature = JSON.parse(geojsonStr)
        const area = turf.area(this.currentFeature)
        this.currentArea = area ? area.toFixed(2) : 0
        // 更新地图预览
        this.countMapLoad++
        this.mapLoading = false
      }
    },

    viewByGeojson() {
      this.currentFeature = JSON.parse(
        this.basicForm.parkRange
      )
      const area = turf.area(this.currentFeature)
      this.currentArea = area ? area.toFixed(2) : 0
      // 更新地图预览
      this.countMapLoad++
      this.mapLoading = false
    },

    onMapLoad({ id, viewer }) {
      _viewer = viewer

      _viewer.scene.imageryLayers.addImageryProvider(
        new Cesium.TiandituImageryProvider({
          mapStyle: null,
          token: 'a49a9220798216424e34b531cb3fa5b2',
          url: 'https://t0.tianditu.gov.cn/img_w/wmts'
        }),
        0
      )
      const geojson = _viewer.dataSources.add(
        Cesium.GeoJsonDataSource.load(this.currentFeature)
      )
      _viewer.flyTo(geojson)
    },

    // handleRemoveImage() {
    //   this.uploadFile = ''
    // },

    // handleChangeImage(file) {
    //   this.uploadFile = file.raw
    // },

    // handlePreviewImage(file) {
    //   if (file.url) {
    //     this.previewImage = file.url
    //   } else if (file.raw) {
    //     this.previewImage = URL.createObjectURL(file.raw)
    //   }
    //   this.previewVisible = true
    // },
    triggerUpload() {
      this.$refs.uploadRef.$el
        .querySelector('input')
        .click()
    },
    handleChangeImage(file) {
      this.uploadFile = file.raw
      this.previewUrl = URL.createObjectURL(file.raw)
    },

    addPlan() {
      this.tableList.push({
        year: '',
        addYearArea: '',
        addYearTotalArea: '',
        addYearNumber: '',
        addYearOutput: ''
      })
    },

    deletePlan(index) {
      this.tableList.splice(index, 1)
    },

    isOptionDisabled(optionValue, currentRow) {
      const selectedYears = this.tableList
        .filter((row) => row !== currentRow)
        .map((row) => row.year)
        .filter(Boolean)

      return selectedYears.includes(optionValue)
    },

    changeType() {
      this.tableList = []
    },

    // 保存信息
    async saveInfo() {
      try {
        const valid =
          await this.$refs.basicFormRef.validate()
        if (valid) {
          try {
            let fileId = ''
            if (this.uploadFile) {
              const image = new FormData()
              image.append('file', this.uploadFile)
              fileId = await uploadFileById(image)
              this.basicForm.parkPicture = fileId.data
            }
            this.basicForm.parkYearRelList = this.tableList
            await addParkInfo(this.basicForm).then(
              (res) => {
                if (res.success) {
                  this.$message.success(
                    this.pkid ? '编辑成功' : '新增成功'
                  )
                  this.$router.push({
                    path: '/dataManagement/carrierReduction/commercialVehicle/list',
                    query: { refresh: Date.now() }
                  })
                } else {
                  this.$message.error(res.message)
                }
              }
            )
          } catch (error) {
            this.$message.error(error)
          }
        }
      } catch (error) {
        // this.$message.error(error);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  .body {
    padding: 10px 0 0 20px;

    // &-left {
    //   width: 70%;
    //   border-right: 1px solid #f1f1f1;
    //   overflow: scroll;
    // }

    // &-right {
    //   flex: 1;
    //   padding-left: 10px;
    // }

    .top {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      padding-right: 10px;
    }
  }

  .shp-upload {
    cursor: pointer;
    height: 0px;
    ::v-deep .el-upload {
      position: relative !important;
      right: 0 !important;
      top: 0 !important;
      transform: none !important;
    }

    &-text {
      position: absolute;
      top: -49px;
      left: 260px;
      color: #00baff;
      min-width: 60px;
      line-height: 14px;
    }

    &-icon {
      position: absolute;
      width: 16px;
      height: 14px;
      top: -49px;
      left: 240px;
      background: url('~@/assets/images/wisdom-construction/upload-file.png');
      background-size: 100% 100%;
    }
  }

  .preview-button {
    position: absolute;
    top: 5px;
    left: 330px;
    background: #497fa3;
    border: 1px solid #497fa3;
    border-radius: 2px;
    color: white;
  }

  .add-btn {
    background: #497fa3;
    border: 1px solid #497fa3;
    border-radius: 2px;
    color: white;
  }

  .line {
    display: flex;
    justify-content: center;
  }

  .table {
    margin-top: 20px;
  }
}

.upload-preview {
  width: 150px;
  height: 150px;
  object-fit: cover;
  cursor: pointer;
  border-radius: 6px;
  border: 1px solid #ddd;
}

.upload-placeholder {
  width: 150px;
  height: 150px;
  border: 1px dashed #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #999;
  border-radius: 6px;
}

.hidden-upload {
  display: none;
}
</style>
